// pages/home/home.js
const util = require('../../utils/util')
// 初始化云数据库环境
let db = wx.cloud.database({
  env: 'junsheng0108-9gsv99le6b9d0ec9'
});
// 连接数据表
let job = db.collection('db_job');
let undone = db.collection('db_undone')
let flag = db.collection('db_flag')
let finish = db.collection('db_finish')

Page({

  /**
   * 页面的初始数据
   */
  data: {
    value: "",
    avatarUrl: '',
    leftHeight: 0,
    rightHeight: 1,
    itemList: [],
    text: [{
      text: "全部任务",
      total: 60,
      src: "../../assets/classify.png"
    }, {
      text: "旗帜",
      total: 1,
      src: "../../assets/flag.png"
    }, {
      text: "未完成",
      total: 6,
      src: "../../assets/undone.png"
    }, {
      text: "已完成",
      total: 10,
      src: "../../assets/finish.png"
    }],
    checked: '',
    checkedList: [],
    isShow: true,
    isOpen: false,
    isNone: false,
    searchList:[],
    isOpenId: false
  },

  onChange(event) {
    this.setData({
      value: event.detail,
    })
  },
  // 取消搜索
  onCancel(){
    this.setData({
      isOpen: false
    })
  },

  //点击跳转页面
  addJump(e){
    console.log('haha',e.currentTarget.dataset.jump);
    let jump = e.currentTarget.dataset.jump
    if(jump == 0){
      wx.navigateTo({
        url: '/pages/allwork/allwork',
      })
    }else if(jump == 1){
      wx.navigateTo({
        url: '/pages/flag/flag',
      })
    }
    else if(jump == 3){
      wx.navigateTo({
        url: '/pages/finish/finish',
      })
    }
    else{
      wx.navigateTo({
        url: '/pages/undone/undone',
      })
    }
  },

  /*输入框搜索商品*/
  async onSearch() {
    var that = this;
    this.setData({
      isOpen: true,
    })
    if(this.data.value.length == 0){
      wx.showToast({
        title: '输入框不能为空',
        icon: 'none'
      })
      return
    }
    //延时执行，防止获取输入框值不对应
    setTimeout(function () {
      /*振动提示*/
      wx.vibrateShort();
      // console.log('aa',that.data.value)
      that.getSearchList(that.data.value)
      that.setData({
        value: ''
      })
    }, 1000)
  },

  // 判断箭头状态值进行下拉
  addSelect(e) {
    let checkIndex = e.currentTarget.dataset.haha;
    for (let i = 0; i < this.data.checkedList.length; i++) {
      if (checkIndex == i) {
        if (this.data.checkedList[i].job_isShow) {
          this.data.checkedList[i].job_isShow = false;
          this.setData({
            [`checkedList[${i}].job_isShow`]: false,
          })
        } else {
          this.data.checkedList[i].job_isShow = true;
          this.setData({
            [`checkedList[${i}].job_isShow`]: true,
          })
        }
      }
    }
  },

  // 判断旗子状态值进行高亮
  async addFlagFunc(e) {
    let checkIndex = e.currentTarget.dataset.flag;
    let id = e.currentTarget.dataset.id;
    for (let i = 0; i < this.data.checkedList.length; i++) {
      if (checkIndex == i) {
        let flag_id = this.data.checkedList[i].job_id;
        let flag_name = this.data.checkedList[i].job_name;
        let flag_time = this.data.checkedList[i].job_time;
        let flag_date = this.data.checkedList[i].job_date;
        let flag_detail = this.data.checkedList[i].job_detail;
        if (this.data.checkedList[i].job_flag) {
          this.data.checkedList[i].job_flag = false;
          this.setData({
            [`checkedList[${i}].job_flag`]: false,
          })
          await this.removeFlag(id)
            .then(content => {
              console.log(content);
              this.getFlagList()
            })
            .catch(error => {
              console.log('1.1', error);
            })
          wx.showToast({
            title: '取消标记',
            icon: 'none'
          })
        } else {
          this.data.checkedList[i].job_flag = true;
          this.setData({
            [`checkedList[${i}].job_flag`]: true,
          })
          await this.addFlag(flag_id, flag_name, flag_time, flag_date, flag_detail)
            .then(content => {
              console.log(content);
              this.getFlagList()
            })
            .catch(error => {
              console.log('1.1', error);
            })
          wx.showToast({
            title: '标记成功',
            icon: 'none'
          })
        }
      }
    }

  },

  // 点击按钮判断勾选的状态值
  async addBtnFunc(e) {
    let checkIndex = e.currentTarget.dataset.index;
    for (let i = 0; i < this.data.checkedList.length; i++) {
      if (checkIndex == i) {
        let val = e.detail.value;
        let undone_id = this.data.checkedList[i].job_id;
        let finish_id = this.data.checkedList[i].job_id;
        let undone_name = this.data.checkedList[i].job_name;
        let finish_name = this.data.checkedList[i].job_name;
        let undone_time = this.data.checkedList[i].job_time;
        let finish_time = this.data.checkedList[i].job_time;
        let undone_date = this.data.checkedList[i].job_date;
        let finish_date = this.data.checkedList[i].job_date;
        let undone_detail = this.data.checkedList[i].job_detail;
        let finish_detail = this.data.checkedList[i].job_detail;
        if (val.length > 0) {
          this.data.checkedList[i].checked = true;
          this.setData({  
            [`checkedList[${i}].checked`]: true,
          })
          await this.addFinish(finish_id, finish_name, finish_time, finish_date, finish_detail)
            .then(content => {
              wx.showToast({
                title: '任务已完成',
                icon: 'success'
              })
              this.getFinishList()
            })
            .catch(error => {
              console.log('1.1', error);
            })
          let id = e.currentTarget.dataset.id;
          await this.removeUndone(id)
            .then(content => {
              this.getUndoneList()
            })
            .catch(error => {
              console.log('1.1', error);
            })
        } else {
          this.data.checkedList[i].checked = false;
          this.setData({
            [`checkedList[${i}].checked`]: false
          })
          let id = e.currentTarget.dataset.id;
          await this.removeFinish(id)
            .then(content => {
              wx.showToast({
                title: '取消已完成',
                icon: 'success'
              })
              this.getFinishList()
            })
            .catch(error => {
              console.log('1.1', error);
            })
          await this.addUndone(undone_id, undone_name, undone_time, undone_date, undone_detail)
            .then(content => {
              this.getUndoneList()
            })
            .catch(error => {
              console.log('1.1', error);
            })
        }
      }
    }
  },

  // 渲染我的列表
  async getJobList() {
    await job.get()
      .then(content => {
        console.log(content)
        let {
          data,
          errMsg
        } = content;
        if (errMsg == "collection.get:ok") {
          this.data.itemList[0].total = data.length;
          this.setData({
            checkedList: data,
            [`itemList[0].total`]: data.length,
          })
          if (data.length == 0) {
            this.setData({
              isShow: true
            })
          } else {
            this.setData({
              isShow: false
            })
          }
        }
      })
  },

  // 根据按钮状态值插入数据表
  addUndone(undone_id, undone_name, undone_time, undone_date, undone_detail) {
    return new Promise((resolve, reject) => {
      undone.add({
          data: {
            undone_id,
            undone_name,
            undone_time,
            undone_date,
            undone_detail,
          }
        })
        .then(content => {
          resolve(content)
        })
        .catch(error => {
          reject(error)
        })
    })
  },
  addFinish(finish_id, finish_name, finish_time, finish_date, finish_detail) {
    return new Promise((resolve, reject) => {
      finish.add({
          data: {
            finish_id,
            finish_name,
            finish_time,
            finish_date,
            finish_detail,
          }
        })
        .then(content => {
          resolve(content)
        })
        .catch(error => {
          reject(error)
        })
    })
  },

  // 根据旗子状态值插入数据表
  addFlag(flag_id, flag_name, flag_time, flag_date, flag_detail) {
    return new Promise((resolve, reject) => {
      flag.add({
          data: {
            flag_id,
            flag_name,
            flag_time,
            flag_date,
            flag_detail,
          }
        })
        .then(content => {
          resolve(content)
        })
        .catch(error => {
          reject(error)
        })
    })
  },

  // 删除标记数据
  removeFlag(id) {
    return new Promise((resolve, reject) => {
      flag.where({
          flag_id: id
        }).remove()
        .then(content => {
          resolve(content)
        })
        .catch(error => {
          reject(error)
        })
    })
  },

  // 根据按钮状态值删除数据表
  removeUndone(id) {
    return new Promise((resolve, reject) => {
      undone.where({
          undone_id: id
        }).remove()
        .then(content => {
          resolve(content)
        })
        .catch(error => {
          reject(error)
        })
    })
  },
  removeFinish(id) {
    return new Promise((resolve, reject) => {
      finish.where({
          finish_id: id
        }).remove()
        .then(content => {
          resolve(content)
        })
        .catch(error => {
          reject(error)
        })
    })
  },

  // 渲染未完成数据
  async getUndoneList() {
    await undone.get()
      .then(content => {
        let {
          data,
          errMsg
        } = content;
        if (errMsg == "collection.get:ok") {
          this.data.itemList[2].total = data.length;
          this.setData({
            [`itemList[2].total`]: data.length,
          })
        }
      })
  },

  // 渲染已完成数据
  async getFinishList() {
    await finish.get()
      .then(content => {
        let {
          data,
          errMsg
        } = content;
        if (errMsg == "collection.get:ok") {
          this.data.itemList[3].total = data.length;
          this.setData({
            [`itemList[3].total`]: data.length,
          })
        }
      })
  },

  // 渲染旗帜数据
  async getFlagList() {
    await flag.get()
      .then(content => {
        let {
          data,
          errMsg
        } = content;
        if (errMsg == "collection.get:ok") {
          this.data.itemList[1].total = data.length;
          this.setData({
            [`itemList[1].total`]: data.length,
          })
        }
      })
  },

  // 搜索相关字段
  async getSearchList(x) {
    await job.where({
        job_name: db.RegExp({
          regexp: '^' + x + '.*',
          options: '(?i)'
        })
      }).get()
      .then(content => {
        console.log(content);
        let {data,errMsg} = content;
        if(errMsg == "collection.get:ok"){
          this.setData({
            searchList: data
          })
        }
        if(data.length == 0){
          this.setData({
           isNone: true
          })
        }else{
          this.setData({
            isNone: false
          })
        }
      })
      .catch(error => {
        console.log(error);
      })
  },

  // 点击跳转登录
  jumpLogin(){
    wx.switchTab({
      url: '../my/my',
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {},

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    this._loadDatas();
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.getJobList();
    this.getUndoneList();
    this.getFinishList();
    this.getFlagList();
    let openid = wx.getStorageSync('openid')
    let avatarUrl = wx.getStorageSync('avatarUrl');
    this.setData({
      avatarUrl: avatarUrl
    })
    if(openid){
      this.setData({
        isOpenId: true,
        isShow: true
      })
      this.getJobList()
    }else{
      this.setData({
        isOpenId: false,
        isShow: false
      })
      this.getJobList()
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    // this.setData({
    //   itemList: [],
    // });
    // wx.stopPullDownRefresh();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    // this._loadDatas();
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  // 瀑布流
  _loadDatas() {
    const that = this;
    let leftHeight = that.data.leftHeight;
    let rightHeight = that.data.rightHeight;
    let itemList = [].concat(that.data.itemList);

    for (let i = 0; i < 4; i++) {
      const type = Math.random() * 10 > 5 ? 1 : 0;
      let tag = '';
      let text = that.data.text[i].text;
      let total = that.data.text[i].total;
      let src = that.data.text[i].src;
      // 添加元素/计算高度
      if (leftHeight > rightHeight) {
        tag = 'right';
        rightHeight += 280;
        if (type == 1) {
          leftHeight -= 30; // 计算高度
        }
      } else {
        tag = 'left';
        leftHeight += 280;
        if (type == 1) {
          rightHeight -= 30; // 计算高度
        }
      }
      itemList.push({
        tag,
        type,
        name: i,
        text,
        total,
        src
      });
    }

    console.log(itemList);
    that.setData({
      itemList,
      rightHeight,
      leftHeight
    });
  },
})